package com.myl.core.exception;

import cn.dev33.satoken.exception.SaSignException;
import cn.hutool.core.util.ObjectUtil;
import com.myl.core.enums.HttpStatusEnum;
import com.myl.core.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;


/**
 * 全局异常处理
 * author: myl <ixiaomu@qq.com> 2023/12/20
 * tips:
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler extends RuntimeException {

    /**
     * 权限校验异常
     */
//    @ExceptionHandler(AccessDeniedException.class)
//    public ResponseResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
//        return ResponseResult.fail(HttpStatusEnum.FORBIDDEN.getCode(), HttpStatusEnum.FORBIDDEN.getMessage());
//    }

    @ExceptionHandler({SaSignException.class})
    public ResponseResult handleSignException(SaSignException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("接口'{}'请求参数异常, '{}'.", requestURI, e.getMessage());
        return ResponseResult.fail(HttpStatusEnum.UNAUTHORIZED.getCode(), e.getMessage());
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseResult handleHttpRequestMethodNotSupported(
            HttpRequestMethodNotSupportedException e,
            HttpServletRequest request
    ) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return ResponseResult.fail(HttpStatusEnum.BAD_METHOD.getCode(), e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceExceptionHandler.class)
    public ResponseResult handleServiceException(ServiceExceptionHandler e) {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        return ObjectUtil.isNotNull(code) ? ResponseResult.fail(code, e.getMessage()) : ResponseResult.fail(e.getMessage());
    }



    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常..", requestURI, e);
        return ResponseResult.fail(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult handleBindException(BindException e) {
        log.error("发生系统异常.'{}'", e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return ResponseResult.fail(402, message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 获取异常信息
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                String message =  errors.get(0).getDefaultMessage();
                return ResponseResult.fail(HttpStatusEnum.BAD_REQUEST.getCode(), message);
            }
        }
        return ResponseResult.fail(HttpStatusEnum.BAD_REQUEST);
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler({RuntimeException.class})
    public ResponseResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return ResponseResult.fail(HttpStatusEnum.BAD_REQUEST.getCode(), e.getMessage());
    }

}
